package cn.itcast.realm;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class SaasRealm extends AuthorizingRealm {


    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;

    /**
     * 认证 判断用户名和密码是否相等
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String email = token.getUsername();
//        password_page是加密的
        String password_page = new String(token.getPassword());
        User user = userService.findByEmail(email);
        if(user!=null){
//            比较密码
            String password_db = user.getPassword();
            if(password_db.equals(password_page)){ // email和密码都是正确
//               需要三个参数：主角user   加密后的密码   当前类名
                return new SimpleAuthenticationInfo(user,password_page,getName());
            }
        }
        return null;   //如果这里一旦return null 那么在subject.login(token)那里就会报错
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("===========================================================================================");

        //        shiro框架在这个方法中想获取当前登录人有哪些权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

//        User user = (User) SecurityUtils.getSubject().getPrincipal();

        User user = (User)  principalCollection.getPrimaryPrincipal();

//        先从redis查询 如果没有数据再查询数据库，记得放入到redis中

        List<Module> moduleList = moduleService.findModuleListByUser(user);
        for (Module module : moduleList) {
            info.addStringPermission(module.getName());  // 告诉了shiro框架 当前登录人有什么权限
        }

        return info;
    }


}
